package com.lk.servlet;

import com.lk.bean.CartItem;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lk
 * @date 2020/4/14 0014 17:50
 * @description:
 */
public class DeleteCartServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        if (id.equals("-1")) {
            req.getSession().removeAttribute("cart");
        } else {
            Map<Integer, CartItem> map = (Map<Integer, CartItem>) req.getSession().getAttribute("cart");
            Map<Integer, CartItem> newMap = new HashMap<Integer, CartItem>();
            for (Map.Entry<Integer, CartItem> entry : map.entrySet()) {
                if (!entry.getValue().getGoods().getGoodsId().equals(id)) {
                    newMap.put(entry.getKey(), entry.getValue());
                }
            }
            req.getSession().removeAttribute("cart");
            req.getSession().setAttribute("cart", newMap);
        }
        req.getRequestDispatcher("cart.jsp").forward(req, resp);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
